package com.dietmanager.formatbuilder;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.dietmanager.model.FoodModel;

/**
 * 
 * @author Petar
 * @description JSONBuilder is class which builds/creates JSON file JSON.Simple
 *              plugin is open source and is from
 *              https://code.google.com/p/json-simple/ >>Please thank that sir
 *              for a nice,great small plugin.
 */

public class JSONBuilder implements FormatBuilder {

	// Instance vars
	public JSONObject dayObject, foodObject, workoutObject;
	public JSONArray foodArray, workoutArray;

	@Override
	public void buildFormat(ArrayList<FoodModel> fm, Date date) {
		dayObject = new JSONObject();
		foodObject = new JSONObject();
		workoutObject = new JSONObject();

		foodArray = new JSONArray();
		workoutArray = new JSONArray();

		for (int j = 0; j < fm.size(); j++) {
			foodObject.put("name", fm.get(j).getName());
			foodObject.put("calories", fm.get(j).getCalories());
			foodObject.put("fat_grams", fm.get(j).getFat());
			foodObject.put("carb_grams", fm.get(j).getCarbohydrates());
			foodObject.put("protein_grams", fm.get(j).getProtein());
			foodArray.add(foodObject);
			foodObject.clear();
		}

		dayObject.put("year", date.getYear());
		dayObject.put("month", date.getMonth());
		dayObject.put("day", date.getDay());
		dayObject.put("consumed", foodArray);
		dayObject.put("expended", workoutArray);

		try {

			FileWriter file = new FileWriter("c:\\DanijelIvanPetar.json");
			file.write(dayObject.toJSONString());
			file.flush();
			file.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
